<template>
  <div class="hazardous-vehicle-review bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-6">危险品车辆预约审核</h2>

    <!-- 搜索栏 -->
    <div class="bg-card text-card-foreground p-6 rounded-lg shadow-sm mb-6">

      <QueryForm :model="search" :formItems="formItems" @search="searchReservations" @reset="resetSearch" />
    </div>

    <div class="mb-4 space-x-2">
      <el-button @click="exportData(reservations, '危险品审核', selectedIds)">导出</el-button>
    </div>

    <!-- 预约列表 -->


    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedReservations" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">

        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_NAME" label="危化品名称" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_TYPE" label="危化品类型" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="TRANSPORT_COMPANY" label="前往企业" header-align="center" align="center"></el-table-column>
        <el-table-column prop="TRANS_STATUS" label="运货状态" header-align="center" align="center"></el-table-column>
        <el-table-column prop="IN_AT" label="预计入园时间" header-align="center" align="center">
          <template #default="scope">
            {{ dayjs(scope.row.IN_AT).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column prop="AUDITOR" label="审核人" header-align="center" align="center">


        </el-table-column>
        <el-table-column prop="STATUS_AUDIT" label="状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.STATUS_AUDIT)">
              {{ (scope.row.STATUS_AUDIT) }}
            </div>

          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.STATUS_AUDIT == '待审核'" type="primary" size="small"
              @click="reviewReservation(scope.row)" link>审核</el-button>
            <el-button v-else type="primary" size="small" @click="viewReservation(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->

    <Pagination v-if="reservations.length" :tableData="reservations" @alltabledata="alltabledata" />

    <!-- 审核对话框 -->
    <!-- <teleport to="body">
      <div v-if="isReviewDialogOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-card p-6 rounded-lg shadow-lg w-full max-w-md">
          <h3 class="text-lg font-bold mb-4">审核预约</h3>
          <form @submit.prevent="submitReview">
            <div class="space-y-4">
              <div>
                <label for="auditResult" class="block text-sm font-medium text-muted-foreground">审核结果：</label>
                <select id="auditResult" v-model="reviewForm.audit_result" required class="input">
                  <option value="通过">通过</option>
                  <option value="拒绝">拒绝</option>
                </select>
              </div>
              <div>
                <label for="comments" class="block text-sm font-medium text-muted-foreground">审核意见：</label>
                <textarea id="comments" v-model="reviewForm.comments" rows="3" class="input"></textarea>
              </div>
            </div>
            <div class="mt-6 flex justify-end space-x-2">
              <button type="button" @click="closeReviewDialog" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">提交</button>
            </div>
          </form>
        </div>
      </div>
    </teleport> -->


    <!--  -->
    <el-dialog class="dialog-from" v-model="isReviewDialogOpen" title="危险化学品运输车辆审核" width="650" destroy-on-close
      align-center>
      <form>

        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>系统单号：</strong>{{ reviewForm.ID }}</div>
          <div><strong>车牌号码：</strong>{{ reviewForm.LICENSE_PLATE }}</div>
          <div><strong>车辆类型：</strong>{{ reviewForm.VEHICLE_TYPE }}</div>
          <div><strong>车牌颜色：</strong>{{ reviewForm.VEHICLE_COLOR }}</div>
          <div><strong>所属运输企业编码：</strong>{{ reviewForm.TRANSPORT_CODE }}</div>
          <div><strong>危化品名称：</strong>{{ reviewForm.HAZARDOUS_MATERIAL_NAME }}</div>
          <div><strong>危化品类别：</strong>{{ reviewForm.HAZARDOUS_MATERIAL_TYPE }}</div>
          <div><strong>重量：</strong>{{ reviewForm.WEIGHT }}</div>
          <div><strong>货运状态：</strong>{{ reviewForm.TRANS_STATUS }}</div>
          <div><strong>前往企业：</strong>{{ reviewForm.TRANSPORT_COMPANY }}</div>
          <div><strong>预计入园时间：</strong>{{ formatDateTime(reviewForm.IN_AT) }}</div>
          <div><strong>预计出园时间：</strong>{{ formatDateTime(reviewForm.EXIT_AT) }}</div>
          <div><strong>道路运输证号：</strong>{{ reviewForm.ROAD_TRANSPORT_ROAD }}</div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>驾驶员信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>驾驶员姓名：</strong>{{ reviewForm.DRIVER_NAME }}</div>
          <div><strong>证件号码：</strong>{{ reviewForm.DRIVER_ID_NUMBER }}</div>
          <div><strong>联系方式：</strong>{{ reviewForm.DRIVER_PHONE }}</div>
          <div><strong>押运员姓名：</strong>{{ reviewForm.ESCORT_NAME }}</div>
          <div><strong>证件号码：</strong>{{ reviewForm.ESCORT_ID_NUMBER }}</div>
          <div><strong>联系方式：</strong>{{ reviewForm.ESCORT_PHONE }}</div>
          <div><strong>行驶证：</strong>{{ reviewForm.DRIVING_LICENSE }}</div>
          <div><strong>有效期起：</strong>{{ formatDateTime(reviewForm.LEN_START_DATE) }}</div>
          <div><strong>有效期止：</strong>{{ formatDateTime(reviewForm.LEN_START_END) }}</div>
          <div><strong>是否有效：</strong>{{ reviewForm.WHETHER_LEN }}</div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>申请信息</span>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">授权类型：</label>
              <el-select style="width: 200px;" :disabled="isViewDialogOpen" v-model="reservationreviewForm.STATUS"
                class="set-select" placeholder="请选择">
                <el-option label="长期" value="长期" />
                <el-option label="临时" value="临时" />
              </el-select>
            </div>
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">到期日期：</label>
            <el-input style="margin: 0; padding: 0;width: 200px;" :disabled="isViewDialogOpen" type="datetime-local"
              v-model="reservationreviewForm.EXPIRATION_DATE" class="input" />
          </div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>其他信息</span>
        </div>
        <div><strong>备注：</strong>{{ reviewForm.STAMP }}</div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button v-if="!isViewDialogOpen" type="primary" @click.prevent="submitReview('通过')">通过</el-button>
          <el-button v-if="!isViewDialogOpen" type="primary" @click.prevent='submitReview("未通过")'>未通过</el-button>
          <el-button @click="closeReviewDialog">取消</el-button>
        </div>
      </form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const selectAll = ref(false)
import { exportData } from '#/utils/exportfile.js'
import { dayjs } from 'element-plus'
const { proxy } = getCurrentInstance()
const apiBaseUrl = computed(() => proxy.$currentUrl + '/api/hazardous-vehicle-reservations')
const tableheard = ['序号', '驾驶员姓名', '车牌号码', '危化品名称', '危化品类型', '前往企业', '运货状态', '预计入园时间', '审核人', '状态']
// 状态变量
const reservations = ref([])
const search = ref({ LICENSE_PLATE: '', DRIVER_NAME: '', STATUS_AUDIT: '' })
const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '审核状态：',
    model: 'STATUS_AUDIT',
    type: 'select',
    placeholder: '请选择',
    options: [

      { label: '待审核', value: '待审核' },
      { label: '未通过', value: '未通过' },
      { label: '通过', value: '通过' },
    ],
  },
])
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const rowKey = (row) => row.ID // 设置行的唯一标识
const selectedIds = ref([])
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const currentPage = ref(1)
const pageSize = ref(10)
const isReviewDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const reservationreviewForm = ref({
  ID: '',
  STATUS_AUDIT: '',
  STATUS: '', //授权类型：
  EXPIRATION_DATE: '', //
  PLATE_NUMBER: '',
  DRIVER_NAME: '',
  VEHICLE_TYPE: '',
  DRIVER_ID_CARD: '',
  RESERVATION_STATUS: ''
})
const reviewForm = ref({})
const viewingReservation = ref(null)

// 计算属性
const totalItems = computed(() => reservations.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const displayedReservations = ref([])
const alltabledata = (data) => {
  displayedReservations.value = data

}
// 方法
const searchReservations = async () => {
  displayedReservations.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/audit/search`, { params: search.value })
    reservations.value = response.data
  } catch (error) {
    console.error('搜索预约失败:', error)
    alert('搜索预约失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {
  search.value = { LICENSE_PLATE: '', DRIVER_NAME: '', STATUS_AUDIT: '' }
  searchReservations()
}

const reviewReservation = (reservation) => {

  reviewForm.value = {

    ...reservation,
  }
  reservationreviewForm.value.ID = reservation.ID,



    isReviewDialogOpen.value = true
}

const viewReservation = (reservation) => {
  isViewDialogOpen.value = true

  reviewForm.value = {

    ...reservation,
  }
  reservationreviewForm.value.ID = reservation.ID,



    isReviewDialogOpen.value = true
}


const closeReviewDialog = () => {
  isReviewDialogOpen.value = false
  isViewDialogOpen.value = false
}

const submitReview = async (data) => {
  reservationreviewForm.value.STATUS_AUDIT = data
  reservationreviewForm.value.PLATE_NUMBER = reviewForm.value.LICENSE_PLATE
  reservationreviewForm.value.DRIVER_NAME = reviewForm.value.DRIVER_NAME
  reservationreviewForm.value.VEHICLE_TYPE = reviewForm.value.VEHICLE_TYPE
  reservationreviewForm.value.DRIVER_ID_CARD = reviewForm.value.DRIVER_ID_NUMBER
  reservationreviewForm.value.RESERVATION_STATUS = data == '通过' ? 'approved' : 'rejected'
  try {
    await axios.post(`${apiBaseUrl.value}/audit/${reservationreviewForm.value.ID}`, reservationreviewForm.value)
    alert('审核提交成功')
    // if (reviewForm.value.audit_result === '通过') {
    //   await axios.post(`${proxy.$currentUrl}/vehicle-pass`, {
    //     LICENSE_PLATE: reviewForm.value.plate_number,
    //     VEHICLE_TYPE: reviewForm.value.vehicle_type,
    //   })

    // }
    closeReviewDialog()
    await searchReservations()
  } catch (error) {
    console.error('提交审核失败:', error)
    alert('提交审核失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewDetails = (reservation) => {
  viewingReservation.value = reservation
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingReservation.value = null
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString()
}


const getStatusClass = (status) => {
  const classMap = {
    '待审核': 'bg-yellow-100 text-yellow-800',
    '通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}
//
const toggleSelectAll = () => {
  reservations.value.forEach(equipment => equipment.selected = selectAll.value)
}
// 生命周期钩子
onMounted(() => {
  searchReservations()
})
</script>

<style scoped>
.input {
  @apply block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>
